package com.irdstudio.apicenter.gateway.comm.pack;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.comm.MaccsPacketUtil;
import com.irdstudio.apicenter.gateway.core.dm.AppChannelForward;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;

/**
 * Http协议下按JSON格式组/解包处理
 * 		通用处理类,如有特殊要求可另起一类进行组/解包
 * @author guangming.li
 * @version 1.0
 * @date 2015-10-13
 */
@Service(value="JsonPackProcessor")
class JsonPackProcessor extends AbstracePackProcessor{
	
	/* 文本日志记录对象(Logback对象) */
	private final static Logger logger = LoggerFactory
			.getLogger(JsonPackProcessor.class);	

	@Override
	public MaccsPacket getReadPackage(AppChannelForward acf,
			MaccsTradeDefineVo tradeDefine, String result) {
		
		MaccsPacket backPacket = null;
		ObjectMapper mapper = new ObjectMapper();
		
		//允许出现特殊字符和转义符
		mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true) ;
		
		//允许出现单引号
		mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true) ;
		
		//如果是海尔指定的TCP方式，则不按Json解析
		//modified by tangxun on 2015/9/23
		if(tradeDefine.getForwardChannelId().equalsIgnoreCase("TCP_CMIS_01")){
			Map<String,Object> tempMap = new HashMap<String,Object>();
			tempMap.put("value", result);
			backPacket = new MaccsPacket(tempMap);
		}else{
			try {
				backPacket = new MaccsPacket(mapper.readValue(
						result, Map.class));
			} catch (JsonParseException e) {
				backPacket = MaccsPacketUtil.makeFailurePacket(e.getMessage());
				e.printStackTrace();
			} catch (JsonMappingException e) {
				backPacket = MaccsPacketUtil.makeFailurePacket(e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				backPacket = MaccsPacketUtil.makeFailurePacket(e.getMessage());
				e.printStackTrace();
			}
		}
		return backPacket;
	}

	/**
	 * 组装成用于发送的JSON字符串
	 */
	@Override
	public String getSendPackage(AppChannelForward acf,
			MaccsTradeDefineVo tradeDefine, MaccsPacket inUvo) {
		String msgBody = "";
		msgBody = MaccsPacketUtil.makeFixedString(inUvo);
		StringBuffer msg = new StringBuffer(acf.getChannelHeadDefine())
				.append(msgBody);
		logger.info("发送信息(目标)：" + msg);
		return msg.toString();
	}
}
